//
//  AppDelegate.m
//  u76ho
//
//  Created by m-air-01 on 15/12/24.
//  Copyright © 2015年 LV. All rights reserved.
//

#import "AppDelegate.h"
#import "WelcomeViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MyMessageVC.h"

#import "AllCompentViewController.h"
#import "ActivityViewController.h"
#import "DeliverSuccessViewController.h"
#import "FriendImpressionViewController.h"
#import "ZNLetterViewController.h"

#define ItunesURL @"https://appsto.re/cn/tfr5ab.i"

///// 个推开发者网站中申请 App 时注册的 AppId、AppKey、AppSecret
//#define kGtAppId @"ktlDjWhgPEA4l9ewdERUa1"
//#define kGtAppKey @"rbjKyBIq8E8Z7E0GagWUcA"
//#define kGtAppSecret @"h8qiKbTvnl9LAVlnaRMA6A"

/// 个推开发者网站中申请 App 时注册的 AppId、AppKey、AppSecret
#define kGtAppId @"pA2j28zyiK9qo5KjPl9Hp"
#define kGtAppKey @"w0SXirWNN96LoAkYeihv"
#define kGtAppSecret @"xsiruftXwF67fiVpT3Bfe6"

#import "MobClick.h"//友盟统计

////蒲公英
//#import <PgySDK/PgyManager.h>
//#import <PgyUpdate/PgyUpdateManager.h>//////////////

@interface AppDelegate ()<UIAlertViewDelegate>


@end

@implementation AppDelegate


//-(void)gotoPuGongYing{
//
//    //启动基本SDK
//    [[PgyManager sharedPgyManager] startManagerWithAppId:@"99cabdaaf5eef7285bcaa951cc067158"];
//    //启动更新检查SDK
//    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:@"99cabdaaf5eef7285bcaa951cc067158"];
//
//}

-(void)setUmengAppkey{
    
       //[MobClick setCrashReportEnabled:NO]; // 如果不需要捕捉异常，
    //[MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取


[MobClick startWithAppkey:@"56fe38e867e58e9f7f000415" reportPolicy:BATCH  channelId:@""];

    
//    [MobClick updateOnlineConfig];  //在线参数配置

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    RootWindow = self.window;//主窗口
    
    [[UINavigationBar appearance]setTintColor:[UIColor grayColor]];
    
    
    //友盟
    [self setUmengAppkey];
    


    
    
    
    
    
    
    //蒲公英
   // [self gotoPuGongYing];
    
    

    //如果登录过访问登录接口
    [self login];

    
    
    self.viewController = [[ViewController alloc]init];
    
    //判断是否第一次使用
    BOOL first = [NSUserDefaults boolForKey:isFirstUse];
    if (!first) {
        //添加引导页
        WelcomeViewController * welcomeVC = [[WelcomeViewController alloc]init];
        self.window.rootViewController = welcomeVC;
    }
    else
    {
        
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:self.viewController];
        nav.navigationBar.hidden = YES;
        self.window.rootViewController = nav;
    }

    
    //设置推送
    // 通过个推平台分配的 appId、 appKey 、appSecret 启动 SDK,注: 该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNS
    [self registerUserNotification];
    // 处理远程通知启动 APP
    [self receiveNotificationByLaunchingOptions:launchOptions];
    
    [U76HONet getVersionandDataBlock:^(NSDictionary *dic) {
//        {
//            versioncode = 11;
//            versionname = "1.0.11";
//        }
        NSLog(@"%@",dic);
        NSString * str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        NSLog(@"%@",str);
        NSString * str2 = [dic objectForKey:@"ios"];
        
        
        if (![str isEqualToString:str2]) {
            
            
            UIAlertView* alertview =[[UIAlertView alloc] initWithTitle:nil message:@"发现新版本!" delegate:self cancelButtonTitle:@"马上升级新版" otherButtonTitles:@"稍后升级",nil];
            
            
            
            [alertview show];
//   [Singleton alerSendMessage:@"有新版本"];
        }
    }];
    
    return YES;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex ==0) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ItunesURL]];
    }

    
    
    
}
-(void)login
{
    //读取用户信息
    [[Singleton share] readUserInformation];
    NetShare * log = request();
    log.isWaiting = NO;
    if ([Singleton share].code) {
        [log POST_URL:[NSString stringWithFormat:@"%@user.php",@"http://www.u76ho.com/"] pram:@{@"action":@"login" ,@"client":@"123456",@"username":[Singleton share].mobile,@"userpwd":[Singleton share].password} finished:^(id responstObj) {
            NSLog(@"假登录 成功列");
            
            int i = [[responstObj objectForKey:@"errcode"] intValue];
            if ( i == 0) {
            
            NSString * token = [responstObj objectForKey:@"token"];
            NSLog(@"登录时保存的token%@",token);
            [Singleton share].token = token;
            
            [[Singleton share] saveUserInformation];
            }
            
            
        } failed:^(NSString *errorMsg) {
            NSLog(@"假登录 失败列");

        }];
    }
    
}
#pragma mark - 用户通知(推送) _自定义方法

/** 注册用户通知 */
- (void)registerUserNotification {
    
    /*
     注册通知(推送)
     申请App需要接受来自服务商提供推送消息
     */
    
    // 判读系统版本是否是“iOS 8.0”以上
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ||
        [UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) {
        
        // 定义用户通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIUserNotificationType types = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        
        // 定义用户通知设置
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        // 注册用户通知 - 根据用户通知设置
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else { // iOS8.0 以前远程推送设置方式
        // 定义远程通知类型(Remote.远程 - Badge.标记 Alert.提示 Sound.声音)
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        
        // 注册远程通知 -根据远程通知类型
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
}

/** 自定义：APP被“推送”启动时处理推送消息处理（APP 未启动--》启动）*/
- (void)receiveNotificationByLaunchingOptions:(NSDictionary *)launchOptions {
    if (!launchOptions)
        return;
    
    /*
     通过“远程推送”启动APP
     UIApplicationLaunchOptionsRemoteNotificationKey 远程推送Key
     */
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"\n>>>[Launching RemoteNotification]:%@", userInfo);
    }
}


#pragma mark - 用户通知(推送)回调 _IOS 8.0以上使用

/** 已登记用户通知 */
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    // 注册远程通知（推送）
    [application registerForRemoteNotifications];
}

#pragma mark - 远程通知(推送)回调

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSString *myToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    myToken = [myToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [GeTuiSdk registerDeviceToken:myToken];
    
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", myToken);
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    [GeTuiSdk registerDeviceToken:@""];
    
    NSLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复 SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
    
#pragma mark - APP运行中接收到通知(推送)处理

/** APP已经接收到“远程”通知(推送) - (App运行在后台/App运行在前台) */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    application.applicationIconBadgeNumber = 1; // 标签
    
    NSLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
}

/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
    // 处理APN
    application.applicationIconBadgeNumber = 0;
    
    NSLog(@"\n>>>[Receive RemoteNotification - Background Fetch]:%@\n\n", userInfo);
    NSLog(@"%@",[userInfo objectForKey:@"aps"]);
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    [Singleton share].cid = clientId;
    [[Singleton share] saveUserInformation];
    if ([Singleton share].code) {
        [U76HONet refreshCidWithaction:@"" cid:[Singleton share].cid code:[Singleton share].code andDataBlock:^(NSDictionary *dic) {
            NSLog(@"上传cid成功了");
        }];
    }
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}


/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayload:(NSString *)payloadId andTaskId:(NSString *)taskId andMessageId:(NSString *)aMsgId andOffLine:(BOOL)offLine fromApplication:(NSString *)appId {
    
   
    
    
    
    // [4]: 收到个推消息
    NSData *payload = [GeTuiSdk retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes length:payload.length encoding:NSUTF8StringEncoding];
    }
    
    NSString *msg = [NSString stringWithFormat:@" payloadId=%@,taskId=%@,messageId:%@,payloadMsg:%@%@", payloadId, taskId, aMsgId, payloadMsg, offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
    
    NSData * jsonData = [payloadMsg dataUsingEncoding:NSUTF8StringEncoding];
    NSError * err;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if (err) {
        NSLog(@"json 解析失败：%@",err);
    }
    NSLog(@"*************%@",dic);
//    {
//        logo = "http://www.u76ho.com/logo.png";
//        name = "\U4f18\U4f01\U4e50\U6d3b";
//        title = "\U4e94\U4e00\U653e\U5047\U901a\U77e5";
//        types = 2;
//        url = "http://www.u76ho.com/user.php?action=article&infoid=2";
    
//    UIApplication * application = [UIApplication sharedApplication];
//    
//    application.applicationIconBadgeNumber = 10;
//
//    }
    if (offLine == YES) {
        NSLog(@"离线消息");
        NSString * type = [dic objectForKey:@"types"] ;
        
        
        
        
        
        //判断是否第一次使用
        BOOL first = [NSUserDefaults boolForKey:isFirstUse];
        if (!first) {
            //添加引导页
            
        }
        else
        {
            
                       if ([type isEqualToString:@"1"]) {
                NSLog(@"$$$$$$$$吐赞评论$$$$$$$$");
                NSString * url = [dic objectForKey:@"url"];
                NSArray * arr = [url componentsSeparatedByString:@"infoid="];
                //个人动态
                AllCompentViewController * allcomentVC = [[AllCompentViewController alloc]init];
                allcomentVC.infoId = arr.lastObject;
                allcomentVC.isAPNS = YES;
                UINavigationController * svc = [[UINavigationController alloc]initWithRootViewController:allcomentVC];
                
                
               self.window.rootViewController = svc;
                
                
            }
            else if ([type isEqualToString:@"2"])
            {
                NSLog(@"$$$$$$$$通知  公告$$$$$$$$");
                NSString * url = [dic objectForKey:@"url"];
                NSArray * arr = [url componentsSeparatedByString:@"id="];
                //主题活动
                ActivityViewController * activityVC = [[ActivityViewController alloc]init];
                activityVC.isAPNS = YES;
                activityVC.infoId = arr.lastObject;
                UINavigationController * svc = [[UINavigationController alloc]initWithRootViewController:activityVC];
                self.window.rootViewController = svc;
            }
            else if ([type isEqualToString:@"3"])
            {
                NSLog(@"$$$$$$$$面试$$$$$$$$");
                NSString * url = [dic objectForKey:@"url"];
                NSArray * arr = [url componentsSeparatedByString:@"id="];
                //投递反馈视图控制器
                DeliverSuccessViewController * deliverVC = [[DeliverSuccessViewController alloc]init];
                deliverVC.isAPNS = YES;
                deliverVC.idm = arr.lastObject;
                UINavigationController * svc = [[UINavigationController alloc]initWithRootViewController:deliverVC];
                self.window.rootViewController = svc;
            }
            else if ([type isEqualToString:@"4"])
            {
                NSLog(@"$$$$$$$$好友印象$$$$$$$$");
                //好友印象
                FriendImpressionViewController * friendImpressionVC = [[FriendImpressionViewController alloc]init];
                friendImpressionVC.isAPNS = YES;
                UINavigationController * svc = [[UINavigationController alloc]initWithRootViewController:friendImpressionVC];
                self.window.rootViewController = svc;
            }
            else
            {
                NSLog(@"$$$$$$$$站内信$$$$$$$$");
                NSString * url = [dic objectForKey:@"url"];
                NSArray * arr = [url componentsSeparatedByString:@"id="];
                //站内信
                ZNLetterViewController * znletterVC = [[ZNLetterViewController alloc]init];
                znletterVC.isAPNS = YES;
                znletterVC.ids = arr.lastObject;
                UINavigationController * svc = [[UINavigationController alloc]initWithRootViewController:znletterVC];
                self.window.rootViewController = svc;
            }
            
        }
        
        //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        
    }
    else
    {
        NSLog(@"在线消息");
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        
        NSString * name = [dic objectForKey:@"name"];
        NSString * title = [dic objectForKey:@"title"];
        
        NSString * GeTuiNews = [NSString stringWithFormat:@"%@ %@",name,title];
        [Singleton alerSendMessage:GeTuiNews];
    }
    
//    UILocalNotification * local = [[UILocalNotification alloc]init];
//    local.userInfo = dic;
//    local.soundName = UILocalNotificationDefaultSoundName;
//    local.alertBody = @"dsadfsd";
//    local.fireDate = [NSDate date];
//    [[UIApplication sharedApplication] scheduleLocalNotification:local];
    
    /**
     *汇报个推自定义事件
     *actionId：用户自定义的actionid，int类型，取值90001-90999。
     *taskId：下发任务的任务ID。
     *msgId： 下发任务的消息ID。
     *返回值：BOOL，YES表示该命令已经提交，NO表示该命令未提交成功。注：该结果不代表服务器收到该条命令
     **/
    [GeTuiSdk sendFeedbackMessage:90001 taskId:taskId msgId:aMsgId];
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
    NSLog(@"\n>>>[GexinSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // [EXT]:通知SDK运行状态
    NSLog(@"\n>>>[GexinSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        NSLog(@"\n>>>[GexinSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
        return;
    }
    
    NSLog(@"\n>>>[GexinSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}
////*****************************************

-(BOOL)application:(UIApplication *)application shouldAllowExtensionPointIdentifier:(NSString *)extensionPointIdentifier
{
    return NO;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
